package com.core.shared.http;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-9-25
 * Time: 上午9:27
 * To change this template use File | Settings | File Templates.
 */
public class HttpPost {

    public static String postSend(Map<String, String> params, String RequestURL) throws IOException {

        String result = null;
        String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; // 内容类型

        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setDoInput(true); // 允许输入流
            conn.setDoOutput(true); // 允许输出流
            conn.setUseCaches(false); // 不允许使用缓存
            conn.setRequestMethod("POST"); // 请求方式
            conn.setRequestProperty("Charset", "utf-8"); // 设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 首先组拼文本类型的参数
            // Map<String, String> params = new HashMap<String, String>();
            // params.put("email", email);
            // params.put("password", password);

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\""
                        + entry.getKey() + "\"" + LINE_END);
                sb.append("Content-Type: text/plain; charset=" + "utf-8"
                        + LINE_END);
                sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
                sb.append(LINE_END);
                sb.append(entry.getValue());
                sb.append(LINE_END);
            }
//            if (file != null) {
//                /**
//                 * 当文件不为空，把文件包装并且上传
//                 */
//                DataOutputStream dos = new DataOutputStream(
//                        conn.getOutputStream());
//                dos.write(sb.toString().getBytes());
//                // file1
//                for (int i = 0; i < file.size(); i++) {
//                    sb = new StringBuilder();
//
//                    sb.append(PREFIX);
//                    sb.append(BOUNDARY);
//                    sb.append(LINE_END);
//                    /**
//                     * 这里重点注意： name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
//                     * filename是文件的名字，包含后缀名的 比如:abc.png
//                     */
//
//                    sb.append("Content-Disposition: form-data; name=\"image"
////                            + (i + 1)
//                            + "\"; filename=\""
//                            + file.get(i).getName() + "\"" + LINE_END);
//                    sb.append("Content-Type:image/jpeg" + LINE_END);
//                    sb.append(LINE_END);
//                    dos.write(sb.toString().getBytes());
//                    InputStream is = new FileInputStream(file.get(i));
//                    byte[] bytes = new byte[1024];
//                    int len = 0;
//                    while ((len = is.read(bytes)) != -1) {
//                        dos.write(bytes, 0, len);
//                    }
//                    is.close();
//                    dos.write(LINE_END.getBytes());
//                }
//                // file
//
//                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
//                        .getBytes();
//                dos.write(end_data);
//                dos.flush();
//
//                /**
//                 * 获取响应码 200=成功 当响应成功，获取响应的流
//                 */
            DataOutputStream dos = new DataOutputStream(
                    conn.getOutputStream());
            dos.write(sb.toString().getBytes());
            int res = conn.getResponseCode();
            // if(res==200)
            // {
            InputStream input = conn.getInputStream();
            StringBuffer sb2 = new StringBuffer();
            int ss;
            while ((ss = input.read()) != -1) {
                sb2.append((char) ss);
            }
            result = sb2.toString();
//            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


}